package com.mmd.openfire_admin.controller;

import java.io.File;
import java.util.Date;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;

import net.coobird.thumbnailator.Thumbnails;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.mmd.openfire_admin.constant.Constant;
import com.mmd.openfire_admin.constant.ErrorCode;
import com.mmd.openfire_admin.pojo.ResponseMsg;
import com.mmd.openfire_admin.pojo.Row;
import com.mmd.openfire_admin.service.RedisService;
import com.mmd.openfire_admin.util.DateUtil;
import com.mmd.openfire_admin.util.JsonUtil;
import com.mmd.openfire_admin.util.MD5Util;
import com.mmd.openfire_admin.util.UUIDGenerator;


@Controller
@RequestMapping( "/open" )
public class FileController {
    
//	@Autowired 
//	RedisService redisService;
	
    @InitBinder     /* Converts empty strings into null when a form is submitted */
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }
    
    
    @RequestMapping(value = "/fileUpload.json",produces="application/json;charset=utf-8", method = RequestMethod.POST)  
    public @ResponseBody ResponseMsg fileUpload(HttpServletRequest request)   {  
    	String username = request.getParameter("username");
    	ResponseMsg retMsg = null;
    		int max_file_size = 1024*1024*10; //10M
	    	try {
	    		System.out.println("11" + DateUtil.DateToString(new Date(), DateUtil.FORMAT_ONE));
	 	        // 设置上下方文  
		        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(  
		                request.getSession().getServletContext());  

		        // 检查form是否有enctype="multipart/form-data"  
		        System.out.println("multipartResolver.isMultipart(request)" + multipartResolver.isMultipart(request));
		        if (multipartResolver.isMultipart(request)) {  
		            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;  
		            
		            
		            Iterator<String> iter = multiRequest.getFileNames();  
		            
		            MultipartFile file = multiRequest.getFile("file"); 
		            while (iter.hasNext()) {  
		                // 由CommonsMultipartFile继承而来,拥有上面的方法.  
		                file = multiRequest.getFile(iter.next());  
		                if (file != null) {  
		                	if (file.getSize() > max_file_size) {
		    		 			retMsg =   new ResponseMsg("文件不能大于"+max_file_size/1024+"KB",ErrorCode.ERROR,null);
		    					return retMsg;		
							}else{
								String originalFilename = file.getOriginalFilename();//文件的上传名称
								if(originalFilename.indexOf(".gif") == -1 && originalFilename.indexOf(".png") == -1 && originalFilename.indexOf(".jpg") == -1 && originalFilename.indexOf(".amr") == -1 && originalFilename.indexOf(".spx") == -1){
									retMsg =   new ResponseMsg("文件格式错误",ErrorCode.ERROR,null);
			    					return retMsg;
								}
								Long curTime = new Date().getTime();
								System.out.println("curTime -- " + curTime);
								StringBuffer fileName = new StringBuffer (curTime + "_" + UUIDGenerator.getUUID());
								File localFile = null;
								if(originalFilename.indexOf(".gif") != -1){
									fileName.append(".gif");
									localFile = new File(Constant.PHOTO_FILE_PATH + fileName);//原图
								}
								if(originalFilename.indexOf(".png") != -1){
									fileName.append(".png");
									localFile = new File(Constant.PHOTO_FILE_PATH + fileName);//原图
								}
								if(originalFilename.indexOf(".jpg") != -1){
									fileName.append(".jpg");
									localFile = new File(Constant.PHOTO_FILE_PATH + fileName);//原图
								}
								if(originalFilename.indexOf(".amr") != -1){
									fileName.append(".amr");
									localFile = new File(Constant.VOICE_FILE_PATH + fileName);//语音文件
								}
								if(originalFilename.indexOf(".spx") != -1){
									fileName.append(".spx");
									localFile = new File(Constant.VOICE_FILE_PATH + fileName);//语音文件
								}
			                    File parent = localFile.getParentFile(); 
			                    if(parent!=null&&!parent.exists()){ 
			                    	parent.mkdirs(); 
			                    } 
			                    //上传文件
			                    file.transferTo(localFile);
			                    
			                    //生成缩略图
			                    if(originalFilename.indexOf(".gif") != -1 || originalFilename.indexOf(".png") != -1 || originalFilename.indexOf(".jpg") != -1){
			                    	Thumbnails.of(Constant.PHOTO_FILE_PATH + fileName)  
			                    	.outputQuality(0.25f) //生成质量  
			                    	.scale(0.2f)  //缩小50%  
			                    	.toFile(Constant.THUMB_FILE_PATH + fileName);
			                    	String thumb_url = Constant.DOMAIN + Constant.THUMB_FILE_URL + fileName;
			                    	String photo_url = Constant.DOMAIN + Constant.PHOTO_FILE_URL + fileName;
			                    	String key = Constant.USER_TOKEN_PRE + username;
			                    	String token = MD5Util.encodeByMD5(key + curTime);
//			                    	redisService.set(key, token);
			                    	Row resultRow = new Row();
			                    	resultRow.put("thumb_url", thumb_url);
			                    	resultRow.put("photo_url", photo_url);
			                    	resultRow.put("token", token);
			                    	retMsg = new ResponseMsg("Ok",ErrorCode.OK, resultRow);
			                    	return retMsg;	
			                    }else if(originalFilename.indexOf(".amr") != -1 || originalFilename.indexOf(".spx") != -1){
			                    	String amr_url = Constant.DOMAIN + Constant.VOICE_FILE_URL + fileName;
			                    	String key = Constant.USER_TOKEN_PRE + username;
			                    	String token = MD5Util.encodeByMD5(key + curTime);
//			                    	redisService.set(key, token);
			                    	Row resultRow = new Row();
			                    	resultRow.put("amr_url", amr_url);
			                    	resultRow.put("token", token);
			                    	retMsg = new ResponseMsg("Ok",ErrorCode.OK, resultRow);
			                    	return retMsg;
			                    }
							}
		            		                    
		                }else{
		                	retMsg =  new ResponseMsg("文件不能为空",ErrorCode.ERROR,null);
		    				return retMsg;
		                }  
		  
		            }  
		        }  
	 			retMsg =  new ResponseMsg("上传失败",ErrorCode.ERROR,null);
				return retMsg;		
		        
			} catch (Exception e) {
				e.printStackTrace();
				return new ResponseMsg("上传失败",ErrorCode.SERVER_ERROR, null);
			}
  } 
    
    @RequestMapping(value = "/iconUpload.json",produces="application/json;charset=utf-8", method = RequestMethod.POST)  
    public @ResponseBody ResponseMsg logoUpload(HttpServletRequest request)   {  
    	String username = request.getParameter("username");
    	ResponseMsg retMsg = null;
    	int max_file_size = 1024*1024*10; //10M
    	try {
    		System.out.println("11" + DateUtil.DateToString(new Date(), DateUtil.FORMAT_ONE));
    		// 设置上下方文  
    		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(  
    				request.getSession().getServletContext());  
    		
    		// 检查form是否有enctype="multipart/form-data"  
    		System.out.println("multipartResolver.isMultipart(request)" + multipartResolver.isMultipart(request));
    		if (multipartResolver.isMultipart(request)) {  
    			MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;  
    			
    			
    			Iterator<String> iter = multiRequest.getFileNames();  
    			
    			MultipartFile file = multiRequest.getFile("file"); 
    			while (iter.hasNext()) {  
    				// 由CommonsMultipartFile继承而来,拥有上面的方法.  
    				file = multiRequest.getFile(iter.next());  
    				if (file != null) {  
    					if (file.getSize() > max_file_size) {
    						retMsg =   new ResponseMsg("文件不能大于"+max_file_size/1024+"KB",ErrorCode.ERROR,null);
    						return retMsg;		
    					}else{
    						String originalFilename = file.getOriginalFilename();//文件的上传名称
    						if(originalFilename.indexOf(".png") == -1 && originalFilename.indexOf(".jpg") == -1){
    							retMsg =   new ResponseMsg("文件格式错误",ErrorCode.ERROR,null);
    							return retMsg;
    						}
    						String fileName = username + ".png";
    						File localFile = new File(Constant.ICON_FILE_PATH + fileName);//原图
    						File parent = localFile.getParentFile(); 
    						if(parent!=null&&!parent.exists()){ 
    							parent.mkdirs(); 
    						} 
    						//上传文件
    						file.transferTo(localFile);
    						
    						//生成缩略图
//    						Thumbnails.of(Constant.PHOTO_FILE_PATH + fileName)  
//    						.outputQuality(0.25f) //生成质量  
//    						.scale(0.2f)  //缩小50%  
//    						.toFile(Constant.THUMB_FILE_PATH + fileName);
    						String photo_url = Constant.DOMAIN + Constant.ICON_FILE_URL + fileName;
    						String key = Constant.USER_TOKEN_PRE + username;
    						String token = MD5Util.encodeByMD5(key + new Date().getTime());
//    						redisService.set(key, token);
    						Row resultRow = new Row();
    						resultRow.put("photo_url", photo_url);
    						resultRow.put("token", token);
    						retMsg = new ResponseMsg("Ok",ErrorCode.OK, resultRow);
    						return retMsg;	
    					}
    					
    				}else{
    					retMsg =  new ResponseMsg("文件不能为空",ErrorCode.ERROR,null);
    					return retMsg;
    				}  
    				
    			}  
    		}  
    		retMsg =  new ResponseMsg("上传失败",ErrorCode.ERROR,null);
    		return retMsg;		
    		
    	} catch (Exception e) {
    		e.printStackTrace();
    		return new ResponseMsg("上传失败",ErrorCode.SERVER_ERROR, null);
    	}
    } 
    
    
    
    
    

 	 
}
